const db = require('../db/index')
const { date } = require('../uitls/dateFormat')


//发表评论
exports.addPublished = (req, res) => {
    const sql = `insert into comments set ?`
    db.query(sql, {
        time: date(new Date()),
        refid: req.body.refid,
        content: req.body.content,
        score: req.body.score,
        userid: req.user.id,
        nickname: req.user.username,
        phone: req.user.phone
    }, (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows != 1) {
            res.cc('提交失败')
        } else {
            let sql2 = `update orders set ispin= 1 where id = ${req.body.orderId}`
            db.query(sql2, (err, results) => {
                if (err) return res.cc(err)
                res.send({
                    status: 200,
                    message: '成功'
                })
            })
        }
    })
}

exports.getCommnetByName = (req, res) => {
    const sql = `select * from comments where nickname like '%${req.query.nickname}%'`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        if (results.length === 0) {
            res.cc('查询评论失败')
        } else {
            res.send({
                status: 200,
                message: '查询评论成功',
                data: results
            })
        }
    })
}

//获取全部评论
exports.getComments = (req, res) => {
    const sql = 'select * from comments'
    db.query(sql, (err, results) => {
        // 执行 SQL 语句失败
        if (err) {
            return res.cc(err.message)
        }
        res.send({
            status: 200,
            message: '获取评论信息成功',
            data: results
        })
    })
}

//根据名字查找评论
exports.getCommnetById = (req, res) => {
    const sql = `select *  from comments where id = ${req.params.id}`
    db.query(sql, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "获取评论成功！",
            data: results[0]
        })
    })
}

//修改评论
exports.updateById = (req, res) => {
    const sql = `update comments set content='${req.body.content}',score=${req.body.score} where id =${req.body.id}`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "修改评论信息成功"
        })
    })
}

//删除评论
exports.delCommnet = (req, res) => {
    const sql = `delete from comments where id = ${req.params.id}`
    db.query(sql, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "删除评论信息成功！",
        })
    })
}